class ProjectsController < ApplicationController
  before_filter :account_required, :login_required
  before_filter :find_user, :except => [:update_manager, :show]
  
  # Show all user's and company's projects
  def index
    @projects = @user.projects
  end
  
  # Show project
  def show
    @manager = User.find(@project.project_manager).name
  end
  
  # Updates manager
  def update_manager
    @project, user_id = Project.find(params[:id]), params[:value]
    user = User.find_by_id(user_id)
    if @project.update_attribute(:project_manager, user_id)
      
      # Assign project for user
      user.projects.find_by_id(@project.id).name rescue user.projects << @project
      render :text => User.find_by_id(user_id).name
    end
  end

  protected
  
  # Find user before filter
  def find_user
    @user = User.find_by_id(params[:user_id], :conditions => ['company_id = ?', current_account.id])
    raise ActiveRecord::RecordNotFound, "Page not found" if @user.nil?
  end
end
